//
//  ICChatViewController+Event.m
//  ICome
//
//  Created by 席鹏飞 on 2016/11/28.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICChatViewController+Event.h"
#import "ICVideoManager.h"
#import "ICAVPlayer.h"
#import "ICRedPacketNetworkManager.h"
static const void *externReceiveView = &externReceiveView;
static const void *externMessageModel = &externMessageModel;
static const void *externGroupId = &externGroupId;

@implementation ICChatViewController (Event)
@dynamic messageModel;
@dynamic groupId;

#pragma mark - tapEvent
// play voice
- (void)chatVoiceTaped:(ICMessageFrame *)messageFrame
             voiceIcon:(UIImageView *)voiceIcon
               redView:(UIView *)redView
{
    
    ICRecordManager *recordManager = [ICRecordManager shareManager];
    recordManager.playDelegate = self;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // 文件路径
    NSString *voicePath = [[ICRecordManager shareManager] recorderPathWithFileName:messageFrame.model.message.fileKey];
    if(![fileManager fileExistsAtPath:voicePath]){
        if([fileManager fileExistsAtPath:[self mediaPath:messageFrame.model.mediaPath]])
        {
            voicePath = [self mediaPath:messageFrame.model.mediaPath];
        }else{
            NSLog(@"语音文件不存在");
            [[ICNetworkManager sharedInstance] downloadRecod:messageFrame.model.message.fileKey fileDir:kAudioPath progress:^(NSProgress *pro) {
            } success:^(NSString *filePath) {
              
                return;
            } failure:^(NSError *error) {
                [MBProgressHUD showError:@"下载失败"];
                return;
            }];
        }
    }
    
    if (messageFrame.model.message.status == 0){
        messageFrame.model.message.status = 1;
        redView.hidden = YES;
        // here to do : database update the readStatus
        [ICMessageDatabase updateMessageStatus:messageFrame.model.message.messageId
                                           gId:self.group.gId
                                        status:ICMessageStatus_read];
        // voice did readed
        [ICMessageHelper voiceDidRead:self.group.gId messageId:messageFrame.model.message.messageId];
    }
    
    if (self.voicePath) {
        if ([self.voicePath isEqualToString:voicePath] || [self.voicePath isEqualToString:[self mediaPath:messageFrame.model.mediaPath]]) { // the same recoder
            self.voicePath = nil;
            [[ICRecordManager shareManager] stopPlayRecorder:voicePath];
            [voiceIcon stopAnimating];
            self.currentVoiceIcon = nil;
            return;
        } else {
            [self.currentVoiceIcon stopAnimating];
            self.currentVoiceIcon = nil;
        }
    }
    
    [[ICRecordManager shareManager] startPlayRecorder:voicePath];
    [voiceIcon startAnimating];
    self.voicePath = voicePath;
    self.currentVoiceIcon = voiceIcon;
}

#pragma mark - ICRecordManagerDelegate

- (void)voiceDidPlayFinished
{
    self.voicePath = nil;
    ICRecordManager *manager = [ICRecordManager shareManager];
    manager.playDelegate = nil;
    [self.currentVoiceIcon stopAnimating];
    self.currentVoiceIcon = nil;
}

// tap image  聊天发送的图片
- (void)showLargeImageWithOglImage:(UIImage *)oglImage
                          WithPath:(NSString *)imgPath
                      withMessageF:(ICMessageFrame *)messageF
                          fromView:(UIView *)from
                       currentCell:(ICChatMessageBaseCell *)cell
{
    NSIndexPath *currentIndexthPath = [self.tableView indexPathForCell:cell];
    NSMutableArray *items = [[NSMutableArray alloc] init];
    UIView *fromView = nil;
    
    for (NSUInteger index = 0; index < self.dataSource.count; index++) {
        ICMessageFrame *modelFrame = [self.dataSource objectAtIndex:index];
        NSString *messageType = modelFrame.model.message.type;
        
        if ([messageType isEqualToString:TypePic]) {
            YYPhotoGroupItem *item = [YYPhotoGroupItem new];
            item.largeImageURL = [NSURL URLWithString:[ICTools getFileOglImageURL:(modelFrame.model.message.fileKey)]];
            item.oglImage = oglImage;
            if (currentIndexthPath.row == index) {
                fromView = from;
                item.thumbView = from;
            } else {
                item.thumbView = nil;
            }
            [items addObject:item];
        }
    }
    
    [self handleTapGesture:nil];
    YYPhotoGroupView *v = [[YYPhotoGroupView alloc] initWithGroupItems:items];
    [v presentFromImageView:fromView toContainer:App_RootCtr.view fromViewC:self animated:YES completion:nil];
}

// tap video
- (void)showLargeVideoWithOglImage:(UIImage *)oglImage
                          fromView:(UIView *)from
                       currentCell:(ICChatMessageBaseCell *)cell
{
    if ([self getAVPlayerFlag]) {
        return;
    }
    
    NSIndexPath *currentIndexthPath = [self.tableView indexPathForCell:cell];
    NSMutableArray *items = [[NSMutableArray alloc] init];
    UIView *fromView = nil;
    
    for (NSUInteger index = 0; index < self.dataSource.count; index++) {
        ICMessageFrame *messageFrame = [self.dataSource objectAtIndex:index];
        NSString *messageType = messageFrame.model.message.type;
        
        if ([messageType isEqualToString:TypeVideo]) {
            NSDictionary *dict = [NSDictionary dictionaryWithJsonString:messageFrame.model.message.lnk];
            NSString *imageUrl = [ICTools getFileOglImageURL:(dict[@"id"])];
            NSString *videoPath = [[ICVideoManager shareManager] videoPathWithFileName:messageFrame.model.message.fileKey];
            ICAVPlayerGroupItem *item = [ICAVPlayerGroupItem new];
            item.largeImageURL = [NSURL URLWithString:imageUrl];
            item.videoPath = videoPath;
            item.fileKey = messageFrame.model.message.fileKey;
            item.oglImage = oglImage;
            if (currentIndexthPath.row == index) {
                fromView = from;
                item.thumbView = from;
            } else {
                item.thumbView = nil;
            }
            [items addObject:item];
        }
    }
    
    [self saveAVPlayerFlag:YES];
    ICAVPlayer *v = [[ICAVPlayer alloc] initWithGroupItems:items];
    [v presentFromVideoView:fromView toContainer:App_RootCtr.view animated:YES completion:nil];
}

- (void)saveAVPlayerFlag:(bool)flag {
    [[NSUserDefaults standardUserDefaults] setBool:flag forKey:@"avPlayerFlag"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (bool)getAVPlayerFlag {
    bool flag = [[NSUserDefaults standardUserDefaults] boolForKey:@"avPlayerFlag"];
    return flag;
}

// 点击红包逻辑处理
- (void)clickRedPacketLogic:(ICClickRedPacketModel *)redPacketModel
               messageModel:(ICMessageModel *)messageModel
                    groupId:(NSString *)gId {

    self.messageModel = messageModel;
    self.groupId = gId;
    
    ICRedPacketReceiveView *view;
    UIWindow *window = [[[UIApplication sharedApplication] windows] lastObject];
    switch ([redPacketModel.pageNo intValue]) {
        case 20:    //单人红包已过期（别人发的）
            view = [[ICRedPacketReceiveView alloc] initWithState:KReceiveState_single_overdue messageModel:messageModel];
            view.promptString = @"该红包已超过24小时，如已领取可在";
            view.delegate = self;
            [view showInView:window];
            break;
        case 18:    //单人红包未过期已领取（别人发的）
        {
            NSDictionary *dict = @{@"model":redPacketModel,
                                   @"sendTime":[NSNumber numberWithInteger:messageModel.message.date]};
            UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_RedPacketResultViewController:dict];
            [self.navigationController pushViewController:viewController animated:YES];
        }
            break;
        case 16:    //单人红包未过期未领取（别人发的）
            view = [[ICRedPacketReceiveView alloc] initWithState:KReceiveState_single_noGet messageModel:messageModel];
            view.delegate = self;
            [view showInView:window];
            break;
        case 28:    //单人红包已过期（我发的）
            view = [[ICRedPacketReceiveView alloc] initWithState:KReceiveState_single_overdue messageModel:messageModel];
            view.promptString = @"该红包已超过24小时，剩余工分已退回可在";
            view.delegate = self;
            [view showInView:window];
            break;
        case 25:    //单人红包未过期已领取（我发的）
        {
            NSDictionary *dict = @{@"model":redPacketModel,
                                   @"sendTime":[NSNumber numberWithInteger:messageModel.message.date]};
            UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_RedPacketResultViewController:dict];
            [self.navigationController pushViewController:viewController animated:YES];
        }
            break;
        case 24:    //单人红包未过期待领取（我发的）
        {
            NSDictionary *dict = @{@"model":redPacketModel,
                                   @"sendTime":[NSNumber numberWithInteger:messageModel.message.date]};
            UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_RedPacketResultViewController:dict];
            [self.navigationController pushViewController:viewController animated:YES];
        }
            break;
        case 4:     //群组红包已过期（别人发的）
            view = [[ICRedPacketReceiveView alloc] initWithState:KReceiveState_group_overdue messageModel:messageModel];
            view.promptString = @"该红包已超过24小时，如已领取可在";
            view.delegate = self;
            [view showInView:window];
            break;
        case 2:     //群组红包未过期已领取（别人发的）
        {
            NSDictionary *dict = @{@"model":redPacketModel,
                                   @"sendTime":[NSNumber numberWithInteger:messageModel.message.date]};
            UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_RedPacketResultViewController:dict];
            [self.navigationController pushViewController:viewController animated:YES];
        }
            break;
        case 1:     //群组红包未过期被抢光（别人发的）
            view = [[ICRedPacketReceiveView alloc] initWithState:KReceiveState_group_noGet messageModel:messageModel];
            view.delegate = self;
            [view showInView:window];
            break;
        case 0:     //群组红包未过期可以抢（别人发的）
            view = [[ICRedPacketReceiveView alloc] initWithState:KReceiveState_group_canGet messageModel:messageModel];
            view.delegate = self;
            [view showInView:window];
            break;
        case 10:    //单人/群组红包未过期已领取（别人发的/我发的）
        {
            NSDictionary *dict = @{@"model":redPacketModel,
                                   @"groupId":gId,
                                   @"sendTime":[NSNumber numberWithInteger:messageModel.message.date]};
            UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_RedPacketResultViewController:dict];
            [self.navigationController pushViewController:viewController animated:YES];
        }
            break;
        case 12:    //群组红包已过期（我发的）
            view = [[ICRedPacketReceiveView alloc] initWithState:KReceiveState_group_overdue messageModel:messageModel];
            view.promptString = @"该红包已超过24小时，剩余工分已退回可在";
            view.delegate = self;
            [view showInView:window];
            break;
        case 9:     //群组红包未过期被抢光（我发的）
            view = [[ICRedPacketReceiveView alloc] initWithState:KReceiveState_group_noGet messageModel:messageModel];
            view.delegate = self;
            [view showInView:window];
            break;
        case 8:     //群组红包未过期可以抢（我发的）
            view = [[ICRedPacketReceiveView alloc] initWithState:KReceiveState_group_canGet messageModel:messageModel];
            view.delegate = self;
            [view showInView:window];
            break;
        default:
            break;
    }
    self.receiveView = view;
}

#pragma mark - ICRedPacketReceiveViewDelegate
//我的红包
- (void)myRedPacketClicked {
  
}

//启
- (void)openImageClicked {
    //为了显示旋转效果延迟一些
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSDictionary *param = @{@"eId":[ICUser currentUser].eId,
                                @"gId":self.groupId,
                                @"redId":self.messageModel.message.fileKey};
        WEAKSELF
        [self getOpenWithParam:param callback:^(ICClickRedPacketModel *redPacketModel) {
            NSDictionary *dict = @{@"model":redPacketModel,
                                   @"sendTime":[NSNumber numberWithInteger:self.messageModel.message.date]};
            UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_RedPacketResultViewController:dict];
            [weakSelf.navigationController pushViewController:viewController animated:YES];
        }];
    });
}

//看看大家
- (void)seeAllBtnClicked {
    NSDictionary *param = @{@"eId":[ICUser currentUser].eId,
                            @"gId":self.groupId,
                            @"redId":self.messageModel.message.fileKey};
    WEAKSELF
    [self getLookListWithParam:param callback:^(ICClickRedPacketModel *redPacketModel) {
        NSDictionary *dict = @{@"model":redPacketModel,
                               @"sendTime":[NSNumber numberWithInteger:self.messageModel.message.date]};
        UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_RedPacketResultViewController:dict];
        [weakSelf.navigationController pushViewController:viewController animated:YES];
    }];
}

#pragma mark - network

// 启
- (void)getOpenWithParam:(NSDictionary *)param
                callback:(void (^)(ICClickRedPacketModel *redPacketModel))callback {
    WEAKSELF
//    [MBProgressHUD showProcessingActivityView:self.view];
    [[ICRedPacketNetworkManager sharedInstance] clickOpenWithParam:param success:^(id object) {
//        [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        [weakSelf.receiveView closeRedPacketReceiveView];
        ICClickRedPacketModel *model = [ICClickRedPacketModel mj_objectWithKeyValues:[object objectForKey:@"data"]];
        callback(model);
    } failure:^(NSError *error) {
//        [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        [weakSelf.receiveView closeRedPacketReceiveView];
        [MBProgressHUD showError:error.domain];
    }];
}

// 看看大家
- (void)getLookListWithParam:(NSDictionary *)param
                    callback:(void (^)(ICClickRedPacketModel *redPacketModel))callback {
    WEAKSELF
    [MBProgressHUD showProcessingActivityView:self.view];
    [[ICRedPacketNetworkManager sharedInstance] lookListWithParam:param success:^(id object) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
       // [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        ICClickRedPacketModel *model = [ICClickRedPacketModel mj_objectWithKeyValues:[object objectForKey:@"data"]];
        callback(model);
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        //[MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:error.domain];
    }];
}

#pragma mark - getter & setter

- (ICRedPacketReceiveView *)receiveView {
    return objc_getAssociatedObject(self, externReceiveView);
}

- (void)setReceiveView:(ICRedPacketReceiveView *)receiveView {
    objc_setAssociatedObject(self, externReceiveView, receiveView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (ICMessageModel *)messageModel {
    return objc_getAssociatedObject(self, externMessageModel);
}

- (void)setMessageModel:(ICMessageModel *)messageModel {
    objc_setAssociatedObject(self, externMessageModel, messageModel, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString *)groupId {
    return objc_getAssociatedObject(self, externGroupId);
}

- (void)setGroupId:(NSString *)groupId {
    objc_setAssociatedObject(self, externGroupId, groupId, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
